// 模块化开发 todoList
init()
function init() {
  initTodoList
}

var initTodoList = (function () {
  var plusBtn = document.getElementsByClassName('j-plus-btn')[0],
    showInput = document.getElementsByClassName('j-show-input')[0],
    addItem = document.getElementsByClassName('j-add-item')[0],
    inputWrap = document.getElementsByClassName('input-wrap')[0],
    inputContent = inputWrap.getElementsByClassName('input-wrap')[0],
    oList = document.getElementsByClassName('')[0],
    inputShow = false

  // 动态展示输入栏
  addEvent(plusBtn, 'click', function () {
    if (inputShow) {
      inputWrap.style.display = 'none'
      inputShow = false
    } else {
      inputWrap.style.display = 'block'
      inputShow = true
    }
  })

  // 添加项目按钮点击事件
  addEvent2(addItem, 'click', function () {
    var content = itemContent.value,
      contentLen = content.length,
      oItems = document.getElementsByClassName('item'),
      itemLen = oItems.length
    if (contentLen <= 0) {
      return
    }

    // 判断是否重复创建
    if (itemLen > 0) {
      for (var i = 0; i < itemLen; i++) {
        itemText = elemChildren(oItems[i])[0].innerText
        if (itemText == content) {
          alert('已存在此项目')
          return
        }
      }
    }

    // 创建 li
    var oLi = document.createElement('li')
    oLi.className = 'item'
    oLi.innerText = itemTpl(val)
    oList.appendChild(oLi)
    // 隐藏输入框
    inputWrap.style.display = 'none'
    inputShow = false
    inputContent.value = ''
  })
  // 利用事件按委托原则
  addEvent(oList, 'click', function (e) {
    var e = e || window.event,
      tar = e.target || e.srcElement,
      className = tar.className,
      oItems = document.getElementsByClassName('item')
    if (className == 'edit-btn fa fa-edit') {
      var itemLen = oItems.length,
        liParent = elemParent(tar, 2),
        // 事件委托: oItems -> liParent
        tarIndex = Array.prototype.indexOf.call(oItems, liParent),
        item
      // 显示输入栏
      inputArea.style.display = 'block'
      inputShow = true

      for (var i = 0; i < itemLen; i++) {
        item = oItems[i]
        item.className = 'item'
      }
      liParent.className = ' active' // 添加背景
      addItem.innerText = '编辑第' + (tarIndex + 1) + '项'
    } else if (className == 'remove-btn fa fa-times') {
      // 删除节点
      elemParent(tar, 2).remove()
    }
  })

  // 模板语法：创建 toItem
  function itemTpl(text) {
    return (
      '<p class="item-content">' +
      text +
      '</p>' +
      '<div class="btn-group">' +
      '<a href="javascript:;" class="fa fa-edit"></a>' +
      '<a href="javascript:;" class="fa fa-items"></a>' +
      '</div>'
    )
  }
})()
